package conpool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import remote.ConfigService;



/*
 * 连接池配置中心
 * */
@Service
public class PoolConfig {
	
	public static List<Map<String, String>> configlist = new ArrayList<>();
	
	public static final String GET_URL = "";

	@Autowired
	ConfigService configService;
    
    //json参数转map
	public ObjectMapper mapper = new ObjectMapper();  
	
    @Value("${config}")
    String config;
	
//  public PoolConfig() {
//		
//	}
    	
	//请求接口获取配置
    public void init() {
        try {
        	System.out.println("自动获取配置："+config);
            URL url = new URL("http://localhost:8764/getconfig?sourceType=mysql");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));  
            String line;  
            StringBuilder sb = new StringBuilder();  
            while ((line = br.readLine()) != null) {
                sb.append(line);  
            }
            br.close();
            connection.disconnect();
            System.out.println("配置内容："+sb.toString());  
        	configlist = mapper.readValue(sb.toString(), List.class);
        } catch (Exception e) {
            e.printStackTrace();  
            System.out.println("请求mysql类型数据源配置失败!");  
        }
        
//      远程调用接口（待完善）
//    	String sb = configService.getConfig("mysql");
//    	try {
//			configlist = mapper.readValue(sb, List.class);
//		} catch (JsonParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (JsonMappingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
    }  
	
	/* 获取配置
	 * 
	 */
	public List<Map<String, String>> getConfig() throws JSONException {
//		try {
//			this.configlist = mapper.readValue(config, List.class);
//		} catch (JsonParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (JsonMappingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		return this.configlist;
	}

}
